from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import urlparse, parse_qs

# --- 全局数据 ---
# 模拟用户数据库
users = [
    {"id": 251001, "name": "张三", "email": "zhangsan@example.com", "about": "杭州"},
    {"id": 251002, "name": "李四", "email": "lisi@example.com", "about": "宁波"}
]
next_user_id = 3

# --- HTML 模板 ---
# 主页模板
def get_index_html():
    # ② 拼数据行
    table_rows = ""
    for user in users:
        table_rows += f"""
                                    <tr>
                                        <td>{user['id']}</td>
                                        <td><strong>{user['name']}</strong></td>
                                        <td><a href="mailto:{user['email']}" class="text-decoration-none">{user['email']}</a></td>
                                        <td><span class="badge bg-secondary">{user['about']}</span></td>
                                    </tr>
        """

    # ① 和 ③ 拼头部和尾部
    html = f"""
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>用户管理系统</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
        <style>
            body{{background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);min-height:100vh;padding:40px 0}}
            .card-shadow{{border:none;border-radius:1rem;box-shadow:0 8px 25px rgba(0,0,0,.15)}}
            .table-hover tbody tr:hover{{background-color:#f1f5ff}}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-12 col-lg-10">
                    <div class="card card-shadow p-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h2 class="mb-0"><i class="bi bi-people-fill text-primary"></i> 已注册用户</h2>
                            <a class="btn btn-primary" href="/add"><i class="bi bi-person-plus"></i> 新增用户</a>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle text-center">
                                <thead class="table-light">
                                    <tr><th>ID</th><th>姓名</th><th>邮箱</th><th>备注</th></tr>
                                </thead>
                                <tbody>
                                    {table_rows}
                                </tbody>
                            </table>
                        </div>
                        <div class="text-muted small mt-3">
                            共 <span class="fw-bold">{len(users)}</span> 位用户
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    """
    return html

# 新增用户表单模板
def get_add_user_html(error_message=""):
    error_html = f'<div class="alert alert-danger">{error_message}</div>' if error_message else ""
    html = f"""
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>新增用户 - 用户管理系统</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
        <style>
            body{{background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);min-height:100vh;padding:40px 0}}
            .card-shadow{{border:none;border-radius:1rem;box-shadow:0 8px 25px rgba(0,0,0,.15)}}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-12 col-md-8 col-lg-6">
                    <div class="card card-shadow p-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h2 class="mb-0"><i class="bi bi-person-plus text-primary"></i> 新增用户</h2>
                            <a class="btn btn-secondary" href="/"><i class="bi bi-arrow-left"></i> 返回</a>
                        </div>
                        {error_html}
                        <form action="/add" method="post">
                            <div class="mb-3">
                                <label for="name" class="form-label">姓名</label>
                                <input type="text" class="form-control" id="name" name="name" required>
                            </div>
                            <div class="mb-3">
                                <label for="email" class="form-label">邮箱</label>
                                <input type="email" class="form-control" id="email" name="email" required>
                            </div>
                            <div class="mb-3">
                                <label for="about" class="form-label">备注</label>
                                <input type="text" class="form-control" id="about" name="about">
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">提交</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    """
    return html

# --- 请求处理器 ---
class UserManagementHandler(BaseHTTPRequestHandler):

    def _send_response(self, content, content_type="text/html; charset=UTF-8", status=200):
        """发送 HTTP 响应的通用方法"""
        self.send_response(status)
        self.send_header("Content-type", content_type)
        self.send_header("Content-Length", str(len(content)))
        self.end_headers()
        self.wfile.write(bytes(content, "utf8"))

    def do_GET(self):
        """处理 GET 请求"""
        if self.path == '/':
            # 主页 - 显示用户列表
            html_content = get_index_html()
            self._send_response(html_content)
        
        elif self.path == '/add':
            # 新增用户页面
            html_content = get_add_user_html()
            self._send_response(html_content)

        elif self.path == '/api/users':
            # API - 获取所有用户的 JSON 数据
            self._send_response(json.dumps(users), "application/json")

        else:
            # 未找到页面
            self._send_response("<h1>404 - 页面未找到</h1>", status=404)

    def do_POST(self):
        """处理 POST 请求"""
        if self.path == '/add':
            # 处理新增用户的表单提交
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            # 将表单数据解析为字典
            form_data = parse_qs(post_data.decode('utf-8'))
            
            # 简单的数据验证
            if not form_data.get('name') or not form_data.get('email'):
                error_msg = "姓名和邮箱为必填项！"
                html_content = get_add_user_html(error_msg)
                self._send_response(html_content)
                return

            # 提取表单数据
            global next_user_id
            new_user = {
                "id": next_user_id,
                "name": form_data['name'][0],
                "email": form_data['email'][0],
                "about": form_data.get('about', [''])[0] # 备注可为空
            }
            next_user_id += 1
            
            # 保存新用户
            users.append(new_user)
            
            # 重定向回主页
            self.send_response(303)
            self.send_header('Location', '/')
            self.end_headers()
        
        else:
            self._send_response("<h1>404 - 页面未找到</h1>", status=404)

# --- 启动服务器 ---
def run(server_class=HTTPServer, handler_class=UserManagementHandler, port=8080):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f"系统已启动!")
    print(f"请在浏览器中访问: http://127.0.0.1:{port}/")
    print("按 Ctrl+C 停止服务...")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print("服务已停止。")

if __name__ == '__main__':
    run()